﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Xunit;
using Xunit.Extensions;

namespace Dojo
{
    public class IntParser : IEnumerable<int>
    {
        private readonly string suppliedNumbers;

        public IntParser(string suppliedNumbers)
        {
            this.suppliedNumbers = suppliedNumbers;
        }

        public IEnumerator<int> GetEnumerator()
        {
            var buffer = new StringBuilder();

            if (string.IsNullOrWhiteSpace(suppliedNumbers))
            {
                yield break;
            }

            foreach (var suppliedNumber in suppliedNumbers)
            {
                if (Char.IsNumber(suppliedNumber))
                {
                    buffer.Append(suppliedNumber);
                    continue;
                }

                var parsedInteger = buffer.ToString();

                if (string.IsNullOrWhiteSpace(parsedInteger))
                {
                    yield return 0;
                }
                else
                {
                    yield return int.Parse(parsedInteger);
                }
                
                buffer = new StringBuilder();
            }

            yield return int.Parse(buffer.ToString());
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }
    }

    public class StringCalculatorTest
    {
        [Theory]
        [InlineData(0, "")]
        [InlineData(0, " ")]
        [InlineData(1, "1")]
        [InlineData(3, "1,2")]
        [InlineData(3, "1;2")]
        [InlineData(3, ";;;;1;2")]
        [InlineData(100, @"45\n45,10")]
        [InlineData(100, @"45:;,/k
45,10")]
        public void Should_return_sum_of_numbers(int expected, string numbers)
        {
            Assert.Equal(expected, new IntParser(numbers).Sum());
        }
    }
}
